package com.dhecp.project.storage.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.dto.IndexConfigDto;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.storage.domain.DeliveryLogistics;
import com.dhecp.project.storage.domain.DeliveryLogisticsDetail;
import com.dhecp.project.storage.enums.DeliveryLogisticsEnum;
import com.dhecp.project.storage.mapper.DeliveryLogisticsMapper;
import com.dhecp.project.storage.service.DeliveryLogisticsDetailService;
import com.dhecp.project.storage.service.DeliveryLogisticsService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 海外仓 控制层
 */
@Controller
@RequestMapping("/storage/deliveryLogistics")
public class HWDeliveryLogisticsController extends BaseModuleController {

    private String prefix = "storage/deliveryLogistics";
    private String moduleTable = ModuleTable.DELIVERY_LOGISTICS;

    @Autowired
    private DeliveryLogisticsMapper deliveryLogisticsMapper;
    @Autowired
    private DeliveryLogisticsDetailService deliveryLogisticsDetailService;
    @Autowired
    private DeliveryLogisticsService deliveryLogisticsService;
    @Autowired
    private SysDictionaryForFieldService sysDictionaryForFieldService;
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     * @Description: 打开查询列表页
     */
    @RequiresPermissions("storage:deliveryLogistics:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/deliveryLogistics"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkLogistics", "yes");
        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "deliveryLogistics");
        return mv;
    }

    /**
     * @Description: 列表页配置数据
     */
    @RequiresPermissions("storage:deliveryLogistics:view")
    @GetMapping("/indexConfig")
    @ResponseBody
    public AjaxResult indexConfig(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
    	
        IndexConfigDto dto = this.getIndexConfig(params);
        
        //导入标记发货模板
        Map<String, Object> params1 = new HashMap<String, Object>();
        params1.put("moduleTable", moduleTable);
        Object importField = dictionaryForFieldService.queryFieldFrontImport(params1);
        dto.setObj(importField);
        AjaxResult ajaxResult = AjaxResult.success(dto);
        return ajaxResult;
    }

    /**
     * @Description: 查询页 列表数据
     */
    @RequiresPermissions("storage:deliveryLogistics:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("stateName", DeliveryLogisticsEnum.StateName.INIT.value);
        List<DeliveryLogistics> list = new ArrayList<DeliveryLogistics>();
        try {
            list = deliveryLogisticsService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryLogistics:view")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(String bid) {
    	
    	DeliveryLogistics deliveryLogistics = deliveryLogisticsMapper.findByBid(bid);
    	
        try {

            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("sonList", deliveryLogisticsDetailService.listByBidLogistics(deliveryLogistics.getBid()));
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            
        	Map<String, Object> params = new HashMap<String, Object>();
            params.put("moduleTable", ModuleTable.DELIVERY_LOGISTICS_DETAIL);
            params.put("entity", new DeliveryLogisticsDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("toolBarWidth", 0);
            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            AjaxResult ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

//    /**
//     * @Description: 查询页 子列表数据
//     */
//    @RequiresPermissions("storage:deliveryLogistics:list")
//    @GetMapping("/sonlist")
//    @ResponseBody
//    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {
//        try {
//
//            params.put("moduleTable", moduleTable2);
//            params.put("entity", new DeliveryLogisticsDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
//            params.put("toolBarWidth", 0);
//            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
//            Map<String, Object> mapList = new HashMap<>();
//            mapList.put("sonList", deliveryLogisticsService.querySonListByBid(params));
//            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
//            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
//            AjaxResult ajaxResult = AjaxResult.success(mapList);
//            return ajaxResult;
//        } catch (Exception e) {
//            return AjaxResult.error(this.getExceptionMessage(e));
//        }
//    }


    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     */
    @RequiresPermissions("storage:deliveryLogistics:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/deliveryLogistics_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 1;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:deliveryLogistics:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }
        
        String bid = params.get("bid").toString();

        try {
            DeliveryLogistics businessData = deliveryLogisticsService.queryByBid(bid);
            Map<String, Object> headData = TypeUtils.entityToMap(businessData);        //表头的业务数据
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);

            if (businessData.getOverseasStockInNo() == null || businessData.getOverseasStockInNo().equals("")){
                mv.addObject("saveEdit",0);
            }else {
                mv.addObject("saveEdit",1);
            }
            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (businessData != null) {
                mv.addObject("detailList", deliveryLogisticsDetailService.listByBidLogistics(businessData.getBid()));//明细数据
                mv.addObject("bid", businessData.getBid());//单号
            }
            mv.addObject("formData", headData);// 表头的业务数据

            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * 保存
     */
    @RequiresPermissions("storage:deliveryLogistics:edit")
    @Log(title = "保存海外仓发货物流单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //System.out.println("params"+params);
            ajaxResult = deliveryLogisticsService.saveData(params);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 导出
     */
    @RequiresPermissions("storage:deliveryLogistics:export")
    @Log(title = "海外仓发货物流数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics());

        List<DeliveryLogistics> list = deliveryLogisticsService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = sysDictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<DeliveryLogistics> util = new ExportExcelUtils<DeliveryLogistics>(moduleTable, new DeliveryLogistics());
        return util.exportExcel(list, fieldList, "海外仓发货装箱数据", "export");
    }

    /**
     * 审核
     */
    //@RequiresPermissions("storage:deliveryLogistics:updateState")
    @Log(title = "海外仓发货物流审核", businessType = BusinessType.UPDATE)
    @PostMapping("/updateState")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateState(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.updateState(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 回退
     */
    //@RequiresPermissions("storage:deliveryLogistics:refuse")
    @Log(title = "海外仓发货装箱回退", businessType = BusinessType.UPDATE)
    @PostMapping("/refuse")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult refuse(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.refuse(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 获取计重单价信息(通过物流名称guid和重量)
     * @param codeLogsticsPattern 物流名称编码
     * @param weight 计重(kg)
     * @param bidBox 海外仓装箱单号
     * @return
     */
    @PostMapping("/getPriceInfo")
    @ResponseBody
    public AjaxResult getPriceInfo(String codeLogsticsPattern, BigDecimal weight, String bidBox) {

        AjaxResult ajaxResult = deliveryLogisticsService.getPriceInfo(codeLogsticsPattern, weight, bidBox);
        return ajaxResult;
    }
}